// 用户数据（收藏与观看历史）存储在 localStorage
const KEY = 'streamvue_user_data'

function loadAll() {
  try { return JSON.parse(localStorage.getItem(KEY) || '{}') } catch { return {} }
}
function saveAll(all) { localStorage.setItem(KEY, JSON.stringify(all)) }
function normUser(username) { return String(username || '').trim() }

export function getUserData(username) {
  const u = normUser(username)
  const all = loadAll()
  return all[u] || { favorites: [], history: [] }
}
export function saveUserData(username, data) {
  const u = normUser(username)
  const all = loadAll()
  all[u] = data
  saveAll(all)
  notify()
}
function notify() {
  try { window.dispatchEvent(new Event('userdata-changed')) } catch {}
}

// 观看历史：保存最新时间，去重，最多 50 条
export function addHistory(username, video) {
  const udata = getUserData(username)
  const entry = {
    id: video.id,
    title: video.title,
    thumb: video.thumb || video.thumbnail || '/images/poster.svg',
    time: new Date().toISOString()
  }
  const idx = udata.history.findIndex(x => x.id === entry.id)
  if (idx !== -1) udata.history.splice(idx, 1)
  udata.history.unshift(entry)
  if (udata.history.length > 50) udata.history.length = 50
  saveUserData(username, udata)
}
export function getHistory(username) {
  const udata = getUserData(username)
  return [...udata.history].sort((a,b) => new Date(b.time) - new Date(a.time))
}
export function clearHistory(username) {
  const udata = getUserData(username)
  udata.history = []
  saveUserData(username, udata)
}

// 收藏：切换收藏状态
export function isFavorite(username, videoId) {
  const udata = getUserData(username)
  return udata.favorites.some(x => x.id === Number(videoId))
}
export function toggleFavorite(username, video) {
  const udata = getUserData(username)
  const idn = Number(video.id)
  const idx = udata.favorites.findIndex(x => x.id === idn)
  if (idx !== -1) {
    udata.favorites.splice(idx, 1)
  } else {
    udata.favorites.push({ id: idn, title: video.title, thumb: video.thumb || video.thumbnail || '/images/poster.svg', time: new Date().toISOString() })
  }
  saveUserData(username, udata)
}
export function getFavorites(username) {
  const udata = getUserData(username)
  return [...udata.favorites].sort((a,b) => new Date(b.time) - new Date(a.time))
}
export function clearFavorites(username) {
  const udata = getUserData(username)
  udata.favorites = []
  saveUserData(username, udata)
}